package com.woniuxy.service.impl;

import com.alibaba.fastjson.JSON;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.woniuxy.entity.Food;
import com.woniuxy.entity.Order;
import com.woniuxy.entity.OrderItem;
import com.woniuxy.entity.dto.AddOrderListDTO;
import com.woniuxy.mapper.FoodMapper;
import com.woniuxy.mapper.OrderMapper;
import com.woniuxy.producer.DelayProducer;
import com.woniuxy.producer.TopicProducer;
import com.woniuxy.service.TakeOutGoodsService;
import com.woniuxy.util.*;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.GetMapping;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @BelongsProject: pigTrotterStore
 * @BelongsPackage: com.woniuxy.service
 * @Author: Quan
 * @Date: 2025/3/21 14:51
 */
@Service
@AllArgsConstructor
public class TakeOutGoodsServiceImpl implements TakeOutGoodsService {
	private FoodMapper foodMapper;
	private TopicProducer topicProducer;
	private DelayProducer delayProducer;
	private OrderMapper orderMapper;
	private ObjectMapper objectMapper;



	/**
	 * @Description: 查询全部已经上架的商品
	 * @Param: []
	 * @return: com.woniuxy.util.ResponseData<?>
	 * @Author: Quan
	 * @Date: 2025/3/21
	 */
	@Override
	public ResponseData<?> queryAll() {
		List<Food> foods = foodMapper.queryAll();
		return ResponseData.ok(foods);
	}

	/**
	 * @Description: 当前端点击下单时，生成订单，
	 * @Param: [addOrderListDTO]
	 * @return: com.woniuxy.util.ResponseData<?>
	 * @Author: Quan
	 * @Date: 2025/3/21
	 * 0、生成订单前，判断这些订单的库存是否足够
	 * 1、把生成订单任务加入队列中
	 * 2、把生成订单明细任务加入队列中
	 * 3、使用队列，对订单的付款信息进行计时，如果15min未付款，也就是订单状态为1，则变为已经取消
	 */
	@Override
	public ResponseData<?> addTakeOutOrder(List<AddOrderListDTO> addOrderMsgList) throws InterruptedException, ParseException, JsonProcessingException {
		// 判断订单的库存是否足够，如果足够，还需要进行库存的减少
		List<Integer> ids = addOrderMsgList.stream()
				.map(AddOrderListDTO::getId)
				.collect(Collectors.toList());
		// 1、生成订单
		// 通过id查询对应的商品信息
		List<Food> foods = foodMapper.batchQueryFood(ids);

		// 生成订单对象
		Order order = new Order();
		order.setOrderNum(String.valueOf(new SnowflakeIdGenerator().nextId()));
		order.setUserId(GetUserIdFromToken.getUserId());
		BigDecimal totalPrice = BigDecimal.ZERO;
//		sellPrice(addOrderMsgList, foods);


		// 转换为Map提高查找效率
		Map<Integer, Integer> orderMsgMap = addOrderMsgList.stream()
				.collect(Collectors.toMap(AddOrderListDTO::getId, AddOrderListDTO::getBuyCount));

		for (Food food : foods) {
			Integer buyCount = orderMsgMap.get(food.getId());
			if (buyCount != null && buyCount > 0) {
				BigDecimal itemPrice = food.getSellPrice().multiply(BigDecimal.valueOf(buyCount));
				totalPrice = totalPrice.add(itemPrice);
			}
		}


		// 将foods与addOrderMsgList均进行遍历，如果id相同，则进行总价格计算
//		foods.forEach(f -> {
//			addOrderMsgList.forEach(e -> {
//				if (f.getId().equals(e.getId())) {
//					totalPrice = totalPrice.add(f.getSellPrice().multiply(BigDecimal.valueOf(e.getBuyCount())));
//				}
//			});
//		});
		order.setTotalPrice(totalPrice);
		order.setStatus(1);



//		orderMapper.addOrder(order);



		// 把订单放入队列中
		String jsonString = JSON.toJSONString(order);
		topicProducer.send("addOrderToMapper", jsonString);

		// 2、生成订单明细加入队列中
		List<OrderItem> orderItems = new ArrayList<>();
		foods.forEach(f -> {
			addOrderMsgList.forEach(e -> {
				if (f.getId().equals(e.getId())) {
					OrderItem orderItem = new OrderItem();
					orderItem.setFoodName(f.getName());
					orderItem.setOrderId(order.getOrderNum());
					orderItem.setPrice(f.getSellPrice());
					orderItem.setFoodId(f.getId());
					orderItem.setBuyCount(e.getBuyCount());
					orderItem.setSumPrice(f.getSellPrice().multiply(BigDecimal.valueOf(e.getBuyCount())));
					try {
						orderItem.setId((int)new SnowflakeIdGenerator().nextId());
					} catch (InterruptedException ex) {
						throw new RuntimeException(ex);
					}
					orderItems.add(orderItem);
				}
			});
		});


//		orderMapper.batchAddOrderItem(orderItems);

		// 将消息详情放入队列
		String orderItemStr = objectMapper.writeValueAsString(orderItems);
		topicProducer.send("addOrderItemToMapper", orderItemStr);
//		3、使用队列，对订单的付款信息进行计时，如果15min未付款，也就是订单状态为1，则变为已经取消
		Integer ttl = 15 * 60 * 1000;
		delayProducer.send("checkOrderStatus", order.getOrderNum(), 10000);
		return ResponseData.ok(order.getOrderNum());
	}

	/**
	 * @Description: 判断是否能够支付
	 * @Param: [orderNum]
	 * @return: com.woniuxy.util.ResponseData<?>
	 * @Author: Quan
	 * @Date: 2025/3/21
	 */
	@Override
	public ResponseData<?> payMoney(String orderNum) {
		Order order = orderMapper.queryOrderByOrderNum(orderNum);
		if (order.getStatus() != 1) {
			return ResponseData.fail(ResponseEnum.DO_NOT_PAYMENT);
		}
		// 说明可以支付，则修改对应状态
		Order payOrder = new Order();
		payOrder.setOrderNum(orderNum);
		payOrder.setStatus(2);

		orderMapper.updateOrderStatus(payOrder);
		return ResponseData.ok();
	}

	/**
	 * @Description: 返回食物名称
	 * @Param: [name]
	 * @return: com.woniuxy.util.ResponseData<?>
	 * @Author: Quan
	 * @Date: 2025/3/21
	 */
	@Override
	public ResponseData<?> queryFoodInfo(String name) {
		List<Food> foods = foodMapper.queryFoodInfo(name);
		return ResponseData.ok(foods);
	}
}



